'''
泰爱保·百万医疗险（2019版）
'''
import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json, time
from common.helper import Helper


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "泰爱保·百万医疗险（2019版）"

    # 生成产品数据
    def genProductInfo(self):

        plan = {

            "planA": {

                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 投保对象
                "payObject": ["儿女"],
                "planCode": ["40"],
                # 保险期限
                "expire": ["1年"]
            },
            "planB": {

                # 年龄段
                "year": [str(i) for i in range(19, 65)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 投保对象
                "payObject": ["本人/配偶"],
                # 计划代码
                "planCode": ["01"],
                # 保险期限
                "expire": ["1年"]

            },
            "planC": {

                # 年龄段
                "year": [str(i) for i in range(20, 65)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 投保对象
                "payObject": ["父母"],

                "planCode": ["50"],
                # 保险期限
                "expire": ["1年"],

            }
        }

        for k in plan:

            introduce = "'" + json.dumps({
                "一般医疗保险金": "300w",
                "重大疾病医疗保险金": "600w",
                "质子重离子医疗保险金": "600w",
                "重大疾病绿色通道": "免费",
            }, ensure_ascii=False) + "'"

            for v in product(plan[k]["year"], plan[k]["socialSec"], plan[k]["payObject"], plan[k]["expire"],
                             plan[k]["planCode"]):
                self.mysql.cursor.execute(
                    domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], introduce))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], introduce))

    # 执行爬虫
    def requestJson(self, dt=None):

        if dt["payObject"] == "儿女":

            data = {"calculateData": {"calstartDate": "2020-01-08 00:00:00", "insuredInfo": [
                {"calinsuredRelationship": dt["planCode"],
                 "calinsuredBirth": "{year}-10-03".format(year=str(2019 - int(dt["year"]))), "minimum": "0",
                 "maximum": "17"}],
                                      "calinsuredAge": dt["year"],
                                      "socialSecurity": "1" if dt["socialSec"] == "Y" else "0", "calpayType": "Y",
                                      "planLiabilityList": [
                                          {"liabilityId": "1019009", "amount": "3000000", "liabilityName": "一般医疗保险金",
                                           "liabilityAmount": "300万"},
                                          {"liabilityId": "1019010", "amount": "6000000", "liabilityName": "重大疾病医疗保险金",
                                           "liabilityAmount": "600万"},
                                          {"liabilityId": "1019008", "amount": "6000000", "liabilityName": "质子重离子医疗保险金",
                                           "liabilityAmount": "600万"},
                                          {"liabilityId": "1019012", "amount": "0", "liabilityName": "",
                                           "liabilityAmount": ""}],
                                      "liabilityContents": [
                                          {"liabilityId": "1019009", "amount": "3000000", "liabilityAmount": "300万",
                                           "liabilityName": "一般医疗保险金"},
                                          {"liabilityId": "1019010", "amount": "6000000", "liabilityAmount": "600万",
                                           "liabilityName": "重大疾病医疗保险金"},
                                          {"liabilityId": "1019008", "amount": "6000000", "liabilityAmount": "600万",
                                           "liabilityName": "质子重离子医疗保险金"},
                                          {"liabilityId": "1019012", "amount": "0", "liabilityAmount": "",
                                           "liabilityName": ""},
                                          {"liabilityId": "", "amount": "", "liabilityAmount": "免费",
                                           "liabilityName": "重大疾病绿色通道"}], "planId": "1019A01L01"},
                    "exchangeData": {"memberId": "", "memberToken": "", "applicationId": "1214462989814251520",
                                     "applicationToken": "f177ee4f03904fe6bbdceb5364889e81",
                                     "workqueueId": "1130368645293522944", "channelId": "3", "platformId": "pc",
                                     "referId": ""}}

        else:

            data = {"calculateData": {"calstartDate": "2020-01-08 00:00:00", "insuredInfo": [
                {"calinsuredRelationship": dt["planCode"],
                 "calinsuredBirth": "{year}-10-03".format(year=str(2019 - int(dt["year"]))), "minimum": "18",
                 "maximum": "65"}],
                                      "calinsuredAge": dt["year"],
                                      "socialSecurity": "1" if dt["socialSec"] == "Y" else "0", "calpayType": "Y",
                                      "planLiabilityList": [
                                          {"liabilityId": "1019009", "amount": "3000000", "liabilityName": "一般医疗保险金",
                                           "liabilityAmount": "300万"},
                                          {"liabilityId": "1019010", "amount": "6000000", "liabilityName": "重大疾病医疗保险金",
                                           "liabilityAmount": "600万"},
                                          {"liabilityId": "1019008", "amount": "6000000", "liabilityName": "质子重离子医疗保险金",
                                           "liabilityAmount": "600万"},
                                          {"liabilityId": "1019012", "amount": "0", "liabilityName": "",
                                           "liabilityAmount": ""}],
                                      "liabilityContents": [
                                          {"liabilityId": "1019009", "amount": "3000000", "liabilityAmount": "300万",
                                           "liabilityName": "一般医疗保险金"},
                                          {"liabilityId": "1019010", "amount": "6000000", "liabilityAmount": "600万",
                                           "liabilityName": "重大疾病医疗保险金"},
                                          {"liabilityId": "1019008", "amount": "6000000", "liabilityAmount": "600万",
                                           "liabilityName": "质子重离子医疗保险金"},
                                          {"liabilityId": "1019012", "amount": "0", "liabilityAmount": "",
                                           "liabilityName": ""},
                                          {"liabilityId": "", "amount": "", "liabilityAmount": "免费",
                                           "liabilityName": "重大疾病绿色通道"}], "planId": "1019A01L01"},
                    "exchangeData": {"memberId": "", "memberToken": "", "applicationId": "1214462989814251520",
                                     "applicationToken": "f177ee4f03904fe6bbdceb5364889e81",
                                     "workqueueId": "1130368645293522944", "channelId": "3", "platformId": "pc",
                                     "referId": ""}}

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=json.dumps(data))

        if r.status_code == 200 and r.json()["code"] == "0":

            price = Helper.decimalParse( r.json()["data"]["sumPremium"] )

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }

            self.mysql.updatePrice(data)

        else:

            data = {

                "name": self.name,
                "id": dt["id"],
                "state": 3
            }

            print("产品流程错误:%d"%dt["id"])

            self.mysql.randTask( data )

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

